package com.louis.iread.adapter;


import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.louis.iread.bean.SearchResultItem;
import com.louis.iread.skin.SkinMgr;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 * Created by louis on 17-3-26.
 */

public class SearchAdapter extends BaseAdapter{
    private Context context;
    private LayoutInflater inflater;
    private int layoutId;
    private int variableId;
    ArrayList<SearchResultItem> list = new ArrayList<>();
    public SearchAdapter(Context context, int layoutId, ArrayList<SearchResultItem> list, int resId) {
        this.context = context;
        this.layoutId = layoutId;
        this.addList(list);
        this.variableId = resId;
        inflater = LayoutInflater.from(context);
    }

    public void addList(ArrayList<SearchResultItem> list) {
        if (this.list == null) {
            this.list = list;
        }
        if (list == null) {
            return;
        }
        this.list.addAll(list);
        Collections.sort(this.list);
        this.notifyDataSetChanged();
    }

    public void clear() {
        if (this.list != null) {
            this.list.clear();
            this.notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewDataBinding dataBinding = null;
        if (view == null) {
            dataBinding = DataBindingUtil.inflate(inflater, layoutId, viewGroup, false);
            view = dataBinding.getRoot();
            view.setTag(dataBinding);
        }else{
            dataBinding = (ViewDataBinding) view.getTag();
        }
        dataBinding.setVariable(variableId, list.get(i));
        SkinMgr.getInstance().applyView(view);
        return view;
    }
}
